/************CURD基本常用API封装*****
 by kevin
 配合datagrid实现的通用表格增删改查
 通用的CURD对象，用于结合datagrid实现表单通用的curd操作api封装
 {
    title: '', //标题
    data: undefined, //列表数据 存在初始化数据时，优先用初始化数据
    url: undefined, //url
    fit2height: false, //是否只能占满父元素(垂直方向)
    pageArea: 页面区域元素,
    loadImd: true, //是否立即加载    
    oprCol: true, //是否需要行操作列  
    treeIconColor: undefined,//树形图标颜色
    oprColWidth: 'auto', //操作列最小宽度，默认自动
    rows: [], //列配置，支持多表头
    idField: 'id', //id字段名称
    checkBox: true, //是否需要复选框
    isTree: false, //是否是树形列表
    pgposition: 'bottom', //分页工具栏位置 top,bottom,both ,none none表示不需要分页栏
    pageSize: 30, //页大小
    toolbar: undefined, //顶部工具栏，参考toolbar组件
    lineClamp: 3,//省略号行数
    openExtendTr: false, //是否默认打开展开行
    topBtnStyle: {
        methodsObject: 'tableMethods',
        style: 'normal', //plain   plain / min  / normal /  big             
        showText: true
    },
    trBtnStyle: {
        align: 'center', //对齐方式，默认是left 、center、right
        methodsObject: 'trMethods',
        style: 'plain', //plain   plain / min  / normal /  big             
        showText: true
    },
    pgBtnNum: 10, //页按钮数量
    pageList: [15, 20, 25, 30, 35, 40, 55, 70, 80, 90, 100], //页大小选择
    pgSummary: true,//是否需要总数量，页数提示
    pgButtonCss: undefined,
    iconCls: undefined, //图标   fa-table
    setParams: undefined, //设置参数
    splitColLine: 'k_table_td_all_line', //分割线样式 k_table_td_v_line、k_table_td_h_line，k_table_td_none_line
    sortField: undefined, //默认排序字段
    sortFieldPrex: '_col_sort_',//排序字段参数前缀
    onDbClickRow: null, // function (tr,data) { },//双击一行时触发 fn(tr,data)
    onClickCell: null, // function (field, value) { },//单击一个单元格时触发fn(field, value)
    onCheck: null, //function () { },//复选事件
    onRowRender: null, // function (tr,data,rownum) { },//行渲染事件，返回true则开启行展开功能 
    onLoaded: null, //function (data) { }//加载完成回调
    onToolCreated: null, //创建工具栏完成回调 
    onTrExtended: null //行展开事件 fn(data, extTr,isShow)
 }
 **/
 function CURD(tableObj, opts) {
    this.gdOpts = $B.extendObjectFn({}, $B.config.curd.table, opts);
    if(opts.methodsObject){
        this.gdOpts.topBtnStyle.methodsObject = opts.methodsObject;
        this.gdOpts.trBtnStyle.methodsObject = opts.methodsObject;
    }
    this.actions = $B.config.curd.actions;
    this.id = this.gdOpts.id;
    this.curWindow = null; //当前打开的window
    this.idField = this.gdOpts.idField ? this.gdOpts.idField : "id";
    var httpHost = $B.getHttpHost();
    if (this.gdOpts.url.indexOf(httpHost) >= 0) {
        this.url = this.gdOpts.url;
    } else {
        this.url = httpHost + this.gdOpts.url;
    }
    var _url = this.url;
    if (this.url && !/gridid=\w+/.test(this.url)) {
        if (this.url.indexOf("?") > 0) {
            _url = this.url + "&gridid=" + this.id;
        } else {
            _url = this.url + "?gridid=" + this.id;
        }
    }
    this.gdOpts.url = _url;
    if (this.gdOpts.fit2height && this.gdOpts.pageArea) { //自适应全屏大小           
        let $page = this.gdOpts.pageArea;
        if (typeof this.gdOpts.pageArea === "string") {
            $page = document.getElementById(this.gdOpts.pageArea.replace("#", ""));
        }
        $B.DomUtils.addClass($page, "k_box_size");
        $page.style.height = "100%";
        let $f = $B.DomUtils.children($page, ".k_form_condition")[0];
        let $g = $B.DomUtils.children($page, ".k_form_grid")[0];
        let need2move = true;
        if ($f.previousSibling && $f.previousSibling === $g) {
            need2move = false;
        }
        $B.DomUtils.addClass($f, "k_box_size");
        $B.DomUtils.addClass($g, "k_box_size");
        let formHeight = $B.DomUtils.outerHeight($f);
        if (need2move) {
            $B.DomUtils.detach($g);
        }
        let css = {
            "position": 'absolute',
            "top": 0,
            "left": 0,
            "height": "100%",
            "width": "100%",
            "border-top": formHeight + "px solid rgba(255,255,255,0)"
        };
        $B.DomUtils.css($g, css);
        $B.DomUtils.css($f, { "position": 'absolute', "top": 0, "left": 0, "width": "100%" });
        if (need2move) {
            $B.DomUtils.prepend($page, $g);
        }
    }
    this.dg = new $B.Table(tableObj, this.gdOpts);
}
CURD.prototype = {
    constructor: CURD,
    setVueForm: function (form) {
        this.vueForm = form;
    },
    /**获取datagrid对象**/
    getDataGrid: function () {
        return this.dg;
    },
    updateTitle: function (title) {
        this.dg.updateTitle(title);
    },
    /** 打开行内嵌页面
    tr:表格行对象
    ****/
    openInner: function (tr) {
        this.dg.openInner(tr);
    },
    /**打开一个操作窗口 一般用于弹出新增、修改窗口
     * args={
        full:false,//是否满屏，当为true时候，高宽无效  
        autoHeight:true,//自动根据内容设置高度
        params:{} ,//参数
        size: { width: 'auto', height: 'auto' },         
        title: '', //标题
        isTop: false,
        iconCls: null, //图标class，font-awesome字体图标
        iconColor: undefined,//图标颜色
        headerColor: undefined,//头部颜色
        toolbar: null, //工具栏对象参考工具栏组件配置说明，可以是创建函数
        toolbarStyle: undefined,//参考工具栏样式定义
        shadow: true, //是否需要阴影
        radius: undefined, //圆角px定义
        header: true, //是否显示头部
        zIndex: 2147483647,//层级
        content: null, //静态内容
        url: '',//请求地址
        dataType: 'html', //当为url请求时，html/json/iframe
        draggable: false, //是否可以拖动
        moveProxy: false, //是否代理移动方式
        draggableHandler: 'header', //拖动触发焦点
        closeable: false, //是否关闭
        closeType: 'hide', //关闭类型 hide(隐藏，可重新show)/ destroy 直接从dom中删除
        expandable: false, //可左右收缩
        maxminable: false, //可变化小大
        collapseable: false, //上下收缩
        resizeable: false,//右下角拖拉大小
        onResized: null, //function (pr) { },//大小变化事件
        onLoaded: null, //function () { },//加载后
        onClose: null, //关闭前
        onClosed: null, //function () { },//关闭后
        onExpanded: null, // function (pr) { },//左右收缩后
        onCollapsed: null, // function (pr) { }//上下收缩后
        onCreated: null //function($content,$header){} panel创建完成事件
    }   
    isUpdated 是否是打开修改窗口
     ***/
    window: function (args, isUpdated) {
        var id,strPrs;
        if ($B.isPlainObjectFn(args.params)) {
            var tmp = [];
            var keys = Object.keys(args.params);
            for (var i = 0, len = keys.length; i < len; ++i) {
                tmp.push(keys[i] + "=" + decodeURIComponent(args.params[keys[i]]));
                if(keys[i] === this.idField){
                    id = args.params[keys[i]];
                }
            }
            strPrs = tmp.join("&");
        }
        if (isUpdated) {
            if (!id) {
                var chkdatas = this.dg.getCheckedData(true);
                if (chkdatas.length === 0) {
                    var msg = typeof args.content === 'undefined' ? $B.config.curd.checkforUpdate : args.content;
                    $B.alert(msg, 1.5);
                    return;
                }
                if (chkdatas.length > 1) {
                    $B.alert($B.config.onlyCheckOneData);
                    return;
                }
                id = chkdatas[0];
                if(strPrs !== ""){
                    strPrs =  strPrs + '&id=' + id;
                }else{
                    strPrs =  'id=' + id;
                }
            }           
            if (!args["iconCls"]) {
                args["iconCls"] = "fa-edit";
            }
        }
        var opts = $B.extendObjectFn({}, $B.config.curd.window, args);
        var pageName = (opts.pageName && opts.pageName !== "") ? opts.pageName : "form";
        opts.url = this.url.replace(/\?\S+/, '').replace(/list/, $B.config.curd.actions.page) + "/" + pageName;
        if (strPrs && strPrs !== '') {
            opts.url = opts.url + "?" + strPrs;
        }
        delete opts.pageName; 
        let onCloseFn = opts.onClosed;
        opts.onClosed = () => {
            if (this.vueForm && this.vueForm.toDestroy) {
                this.vueForm.toDestroy();
                console.log("colsed destroy vue form!");
            }
            this.vueForm = undefined;
            if (onCloseFn) {
                onCloseFn();
            }
        };
        this.curWindow = $B.window(opts);
        return this.curWindow;
    },
    /**
     * 用于$B.window()与curd.window()共用页面时候
     * 便于内部curdObj.add/update能够自动关闭窗口
     * **/
    setOpenWindow: function (win) {
        this.curWindow = win;
    },
    /*** 关闭当前打开的窗口***/
    close: function () {
        if (this.curWindow !== null && this.curWindow.close) {
            this.curWindow.close();
        }
        this.curWindow = null;
    },
    closeWindow: function () {
        this.close();
    },
    /**新增args=
     {
        data:{}, //提交的参数
        ok:function(data,message){}//成功处理后的回调,
        final:function(res){} //无论成功，失败都回调的事件
    }/
     args = {f1:xx,f2:xx...};
     onReturnFn:回调或者按钮
     ***/
    add: function () {
        console.log(arguments);
        var args, onReturnFn,btn;
        for(let i = 0 ;i < arguments.length ;i++){
            let arg = arguments[i];
            if(typeof arg === "function"){
                onReturnFn = arg;
            }else if($B.Dom.isElement(arg)){
                btn = arg;
            }else{
                args = arg;
            }
        }
        let actions = $B.config.curd.actions;
        var url = this.url.replace(/\?\S+/, '').replace(/list/, actions.add);
        this._save(args, url, onReturnFn,btn);
    },
    /**
     * 更新 args={
        data:{},
        ok:function(data,message){},
        final:function(res){}
    }/
     args = {f1:xx,f2:xx...};
     onReturnFn:回调或者按钮
     * **/
    update: function () {
        var args, onReturnFn,btn;
        for(let i = 0 ;i < arguments.length ;i++){
            let arg = arguments[i];
            if(typeof arg === "function"){
                onReturnFn = arg;
            }else if($B.Dom.isElement(arg)){
                btn = arg;
            }else{
                args = arg;
            }
        }
        let actions = $B.config.curd.actions;
        var url = this.url.replace(/\?\S+/, '').replace(/list/, actions.update);
        this._save(args, url, onReturnFn,btn);
    },
    /**add / update 的内部调用函数**/
    _save: function (args, url, onReturnFn,btn) {        
        var _this = this;
        var opts;
        if (args.data && (typeof args.url !== "undefined" || typeof args.fail === "function" || typeof args.ok === "function" || typeof args.final === "final")) {
            opts = args;
        } else {
            opts = {
                waiting: true,
                data: args,
                ok: function (message, data, res) {
                    _this.reload({
                        page: 1
                    });
                    setTimeout(()=>{
                        _this.close();
                    },1);                     
                    if (typeof onReturnFn === "function") {
                        onReturnFn(res);
                    }                                      
                },
                fail: function (message, res) {
                    $B.error(message, 1.5);
                    if (typeof onReturnFn === "function") {
                        onReturnFn(res);
                    }
                }
            };
        }
        opts.url = url;       
        $B.request(opts, btn);
    },
    /**删除数据 idArray = 需要删除的id数组
     * args:其他附加的参数
     * ***/
    deleteData: function (idArray, args) {
        return this._del({}, idArray, args);
    },
    /**删除复选的数据 args={
        content:'提示信息',
        params:{},
        ok:function(data,message){},
        final:function(res){},
        fail:function(){}
        }
     * **/
    delChecked: function (args) {
        var chkdatas = this.dg.getCheckedData(true);
        return this._del(args, chkdatas);
    },
    _del: function (args, idArray, prs) {
        if (idArray.length === 0) {
            var msg = (!args || typeof args.content === 'undefined') ? $B.config.curd.checkforDelete : args.content;
            $B.alert(msg,1.5);
            return;
        }
        var _this = this;
        return $B.confirm({
            content: $B.config.curd.confirmDelete,
            okFn: function () {
                var deleteAll = _this.dg.getRowCount() === idArray.length;
                var url = _this.url.replace(/\?\S+/, '').replace(/list/, $B.config.curd.actions.del);
                var params = { idList: idArray.join(",") };
                if (prs) {
                    $B.extendObjectFn(params, prs);
                }
                if (args && args.params) {
                    $B.extendObjectFn(params, args.params);
                }
                var opts = {
                    waiting: true,
                    url: url,
                    data: params,
                    ok: function (message, data) {
                        _this.close();
                        if (deleteAll) {
                            _this.reload({
                                page: 1
                            });
                        } else {
                            _this.refresh();
                        }
                    }
                };
                $B.request(opts);
            }
        });
    },
    /**
     * 获取复选的数据
     * ***/
    getCheckedData: function () {
        return this.dg.getCheckedData();
    },
    /**
     * 获取复选的数据id
     * ***/
    getCheckedId: function () {
        return this.dg.getCheckedData(true);
    },
    /**根据参数查询多条数据
     args={
        params:{},
        ok:function(data,message){}
    }
     ****/
    query: function (args) {
    },
    /**根据id查询单条数据
     args={
        id:id
        ok:function(data,message){}
        }
     ***/
    get: function (args) { },
    /**
     * 重新加载
     * args={} 查询参数
     * ****/
    reload: function (args) {
        this.dg.reload(args);
    },
    /**
     * 采用上一次查询的参数刷新当前页
     * **/
    refresh: function () {
        this.dg.refresh();
    }
};
$B["CURD"] = CURD;